import * as cc from "cc";
import { resourcesMgr } from "../../framework/loader/ResourcesMgr";
import { Locator } from "../../framework/utils/Locator";
const { ccclass, } = cc._decorator;
/**
 * Predefined variables
 * Name = UIBase
 * DateTime = Sun Mar 20 2022 15:06:42 GMT+0800 (中国标准时间)
 * Author = 272493431
 * FileBasename = UIBase.ts
 * FileBasenameNoExtension = UIBase
 * URL = db://assets/scripts/framework/ui/UIBase.ts
 * ManualUrl = https://docs.cocos.com/creator/3.4/manual/zh/
 *
 */
 let idx = 0;

export class UIBaseTest{
    uuid = `UIBaseTest_${idx++}`;


    node: cc.Node;
    
    // 缓存下查找过的结点
    nodeCache: Record<string,cc.Node> = {};
    onCtor(node: cc.Node | any){
        this.node = node;
        this.onLoaded();
    }
    onLoaded(){

    }

    onUnloaded(){

    }

    /**
     * 窗口激活
     */
    onActive(){
        console.log(`UIBase-> ${this.uuid} 激活`);
        
    }

    /**
     * 窗口冻结
     */
    onFreeze(){
        console.log(`UIBase-> ${this.uuid} 冻结`);
    }

    registeButtonClick(node: cc.Node | cc.Button | string,cb: ()=> void){
        if(typeof node === 'string'){
            node = this.find(node);
        }
        if(node instanceof cc.Button){
            node = node.node;
        }
        node.on("click",()=> cb());
    }

    find(path: string,parentOrRefresh?: cc.Node | boolean,refresh?: boolean){
        let parent: cc.Node = parentOrRefresh as cc.Node;

        if(refresh === undefined){
            if(typeof parentOrRefresh === 'boolean'){
                refresh = parentOrRefresh;
            }else if(parentOrRefresh != undefined){
                parent = parentOrRefresh;
            }else if(parentOrRefresh == undefined){
                parent = this.node;
            }
        }

        let node = this.nodeCache[path];

        if(refresh || !node){
            node = Locator.locateNode(parent,path);
        }

        if(node && this.node === parent){
            this.nodeCache[path] = node;
        }
        return node;
    }
    findComponent<T extends cc.Component>(path: string,type: cc.__private._types_globals__Constructor<T>,parentOrRefresh?: cc.Node | boolean,refresh?: boolean): T | null{
        let node = this.find(path,parentOrRefresh,refresh);
        if(node){
          return  node.getComponent(type);
        }
        return null;
    }
}
